package com.chen.demo.javase.juc.mypoll;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author chenhongwei
 * @date 2020/2/25 15:59
 **/
public class MyThreadPool {

    private final Integer WORK_NUM_DEFAULT = 5;

    private final Integer MAX_TASK_COUNT = 100;

    private BlockingQueue<Runnable> taskQueue;

    private WorkThread[] workThreads;

    private Integer workNum;

    private Integer maxTaskCount;

    public MyThreadPool() {
        new MyThreadPool(WORK_NUM_DEFAULT, MAX_TASK_COUNT);
    }

    public MyThreadPool(Integer workNum, Integer maxTaskCount) {
        this.workNum = workNum;
        this.maxTaskCount = maxTaskCount;

        workThreads = new WorkThread[this.workNum];
        taskQueue = new ArrayBlockingQueue<>(this.maxTaskCount);
        for (WorkThread workThread : workThreads) {
            workThread.start();
        }
    }


    public void execute(Runnable runnable) throws InterruptedException {
        taskQueue.put(runnable);
    }


    private class WorkThread extends Thread {
        @Override
        public void run() {
            while (!isInterrupted()) {
                try {
                    Runnable runnable = taskQueue.take();
                    runnable.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
